import Router from '@koa/router'
import { map, pick } from 'lodash'
import { insert, like, select, delete as sqlDelete, update, eq,in  as $in} from 'mysql-bricks'
import { query } from '../models'

/**
 * 获取停车场列表
 */
export const getParkSpacePageController: Router.Middleware = async (ctx) => {
    const likePicked = pick(ctx.query, ['name', 'number'])
    const likeWhereExp = map(likePicked, (v, k) => like(k, `%${v}%`))
    const eqPicked = pick(ctx.query, ['parkId', 'type', 'status'])
    const eqWhereExp = map(eqPicked, (v, k) => eq(k, v))
    const page = ctx.query.page || 1
    // 生成sql
    const sql = select()
        .from('park_space')
        .where(...likeWhereExp, ...eqWhereExp)
        .limit(+ctx.query.limit || 10)
        .offset((+page - 1) * 10)
        .toString()
    console.log(sql)
    // 执行sql
    const res = await query(sql)
    const total = await query('select count(*) as total from park_space')
    // 返回数据
    ctx.body = {
        total: total[0].total,
        rows: res,
    }
}

/**
 * 获取停车场下拉框列表
 */
export const getParkSpaceOptionListController: Router.Middleware = async (
    ctx
) => {
    // 生成sql
    const sql = select('id', 'name').from('park_space').toString()
    // 执行sql
    const res = await query(sql) as any

    // 返回数据
    ctx.body = res
}

/**
 * 添加停车场
 */
export const postParkSpaceController: Router.Middleware = async (ctx) => {
    // 获取请求参数
    const data = ctx.request.body
    // 生成sql
    const sql = insert().into('park_space').values(data).toString()
    // 执行sql
    const res = (await query(sql)) as any
    // 返回数据
    ctx.body = {
        id: res.insertId,
    }
}

/**
 * 修改停车场信息
 */
export const putParkSpaceByIdController: Router.Middleware = async (ctx) => {
    const id = +ctx.params.id!
    const data = ctx.request.body
    // 生成sql
    const sql = update('park_space', data).where('id', id).toString()
    // 执行sql
    const res = await query(sql)
    // 返回数据
    ctx.body = true
}

/**
 * 删除停车场
 */
export const deleteParkSpaceByIdController: Router.Middleware = async (ctx) => {
    const id = +ctx.params.id!
    // 生成sql
    const sql = sqlDelete().from('park_space').where('id', id).toString()
    // 执行sql
    const res = await query(sql)
    // 返回数据
    ctx.body = true
}

export const deleteParkSpaceByMulIdController = async ( ctx ) => {

    const ids = ctx.query.ids.toString()
   
    const idArr = ids.split(',')
    
    const sql = sqlDelete().from('park_space').where($in('id', idArr)).toString()
    
    const res =await query(sql)
    ctx.body =true
}

